package com.oceansoft.mobile.weixin.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.weixin.entity.WX_Reply;
import com.oceansoft.mobile.weixin.entity.message.req.SuperMessage;
import com.oceansoft.mobile.weixin.entity.message.resp.Article;
import com.oceansoft.mobile.weixin.entity.message.resp.NewsMessageResp;
import com.oceansoft.mobile.weixin.entity.message.resp.TextMessageResp;
import com.oceansoft.mobile.weixin.util.MessageUtil;
import com.oceansoft.mobile.weixin.util.WX_Constants;

/** 
 * 核心服务类 
 */
@Component
public class CoreService {
	
	@Resource
	private WechatService wechatService;
	
	@Resource
    private ICommonDao commonDao;
	
	/** 
	 * 处理微信发来的请求 
	 * 封装用户发送的消息，并保存用户信息，并进行相应的回应
	 * @param request 
	 * @return 
	 */
	public String processRequest(HttpServletRequest request) {
		String respXML="";
		try{
			Map<String,String> requestMap=MessageUtil.parseXml(request);
			/***********以下测试使用*****************/
//			Map<String,String> requestMap=new HashMap<String, String>(); 
//			requestMap.put("FromUserName", "oGdMluHSjznzg3u6am3GP5fexaBU");
//			requestMap.put("ToUserName", "gh_66a6649f11b2");
//			requestMap.put("MsgType", "text");
//			requestMap.put("MsgId", "6029236001827752767");
//			requestMap.put("Content", "3");
			/***********以上测试使用******************/
			
			String msgType=requestMap.get("MsgType");
			SuperMessage sm=new SuperMessage();
			sm.setFromUserName(requestMap.get("FromUserName"));
			sm.setToUserName(requestMap.get("ToUserName"));
			sm.setContent(requestMap.get("Content"));
			sm.setCreateTime(new Date().getTime());
			sm.setMsgType(msgType);
			//System.out.println("msgType========="+msgType);
			if(null!=requestMap.get("MsgId"))
				sm.setMsgId(Long.valueOf(requestMap.get("MsgId")));
			boolean flag=true;
			if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){
				//System.out.println("---文本-----");
				String content=requestMap.get("Content");
				respXML = getReplyByKey(sm, content);
				wechatService.addWXUser(sm.getFromUserName(), sm.getToUserName());
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
				sm.setPicUrl(requestMap.get("PicUrl"));
				sm.setMediaId(requestMap.get("MediaId"));
				wechatService.addWXUser(sm.getFromUserName(), sm.getToUserName());
				//TODO 处理并回应
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)){
				sm.setMediaId(requestMap.get("MediaId"));
				sm.setFormat(requestMap.get("Format"));
				wechatService.addWXUser(sm.getFromUserName(), sm.getToUserName());
				//TODO 处理并回应
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)){
				sm.setMediaId(requestMap.get("MediaId"));
				sm.setThumbMediaId(requestMap.get("ThumbMediaId"));
				//TODO 处理并回应
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)){
				sm.setLabel(requestMap.get("Label"));
				sm.setLocation_X(requestMap.get("Location_X"));
				sm.setLocation_Y(requestMap.get("Location_Y"));
				sm.setScale(requestMap.get("Scale"));
				//TODO 处理并回应
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)){
				sm.setTitle(requestMap.get("Title"));
				sm.setDescription(requestMap.get("Description"));
				sm.setUrl(requestMap.get("Url"));
				//TODO 处理并回应
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
				flag=false;
				//事件类型
				String eventType=requestMap.get("Event");
				//System.out.println("eventType======="+eventType);
				//用户关注时，如果已经有这个用户则更新用户信息；没有则记录用户信息，并进行智能回复；
				if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)){
					System.out.println("-----关注----");
			 		wechatService.subscribeWXUser(sm.getFromUserName(), sm.getToUserName());
					//返回关注回复
					WX_Reply reply=wechatService.queryReplySub(sm.getToUserName());
					if(reply!=null&&WX_Constants.REPLY_MATERIAL_TEXT.equals(reply.getMaterial_type())){
						String content=wechatService.queryReplyMaterialText(reply);
						if(null!=content){
							sm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
							sm.setContent(content.toString());
							respXML=doTextMsg(sm);
						}
					}
				}
				//用户取消关注时，只更新信息，不需要任何响应
				else if(eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)){
					System.out.println("-----取消关注----");
					commonDao.updateColumn2("wx_user", "openid", sm.getFromUserName(), "subscribe", 0, "subscribe_time", new Date().getTime());
					
				}else if(eventType.equals(MessageUtil.EVENT_TYPE_CLICK)){
					String eventKey=requestMap.get("EventKey");
					//菜单事件返回信息
					respXML = getReplyByKey(sm, eventKey);
					
				}else if(eventType.equals(MessageUtil.EVENT_TYPE_SCAN)){
					System.out.println("=========二维码扫描");
				}
				else if(eventType.equals(MessageUtil.EVENT_TYPE_VIEW)){
					String eventKey=requestMap.get("EventKey");
					//System.out.println("eventKey ========="+eventKey);
					respXML = getReplyByKey(sm, eventKey);
				}
			}
			if(flag){//保存用户发送的各类型信息，事件类型的不需要保存消息
				wechatService.saveUserMsg(sm);
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return respXML;
	}
	
	/**
	 * 根据关键词返回内容（图文或者文本等）
	 * 适用于菜单事件，关键词回复
	 * @param sm
	 * @param eventKey
	 * @return
	 */
	private String getReplyByKey( SuperMessage sm,String eventKey) {
		String respXML="";
		WX_Reply reply=wechatService.queryReplyKey(sm.getToUserName(),eventKey);
		//收集一下网友的信息
		/*try{
			commonDao.updateOne("insert into wx_user_msg values(0,'"+sm.getFromUserName()+"','"+eventKey+"',now())");
		}catch(Exception e)
		{
			e.printStackTrace();
		}*/
		if(null==reply)
		{
			String content = sm.getContent();
			sm.setContent("欢迎您的关注，期待您的互动！交通违法处理、掌上车管、智能出行、自助移车、事故快撤、开锁求助..……“大苏州微警务”竭诚为您服务！遇有“紧急”报警求助，还请拨打“110”！");
			respXML=doTextMsg(sm);
			sm.setContent(content);
			return respXML ;
		}
		//System.out.println("reply.getMaterial_type()=============="+reply.getMaterial_type());
		if(null!=reply){
			if(WX_Constants.REPLY_MATERIAL_TEXT.equals(reply.getMaterial_type())){
				String ct=wechatService.queryReplyMaterialText(reply);
				if(StringUtils.hasText(ct)){
					if(ct.indexOf("openId=test")>-1)
					{
						ct = ct.replace("openId=test", "openId="+sm.getFromUserName());
					}
					sm.setContent(ct);
					respXML=doTextMsg(sm);
				}
			}else if(WX_Constants.REPLY_MATERIAL_ARTICLE.equals(reply.getMaterial_type())){
				List<Article> artList=wechatService.queryReplyMaterialArticel(reply);
				if(null!=artList&&artList.size()>0){
					if("999".equals(eventKey)){
						for(Article art:artList){
							art.setUrl(art.getUrl()+"?openId="+sm.getFromUserName());
						}
					}
					for (Article article : artList) {
						String url = article.getUrl();
						if(StringUtils.hasText(url)&&url.indexOf("openId=test")>-1)
						{
							url = url.replace("openId=test", "openId="+sm.getFromUserName());
							article.setUrl(url);
						}
					}
					respXML=doArticleMsg(sm,artList);
				}
			}else if(WX_Constants.REPLY_MATERIAL_ARTICLE_LINK.equals(reply.getMaterial_type())){
				//本处的图文回复，要先获取用户信息。主要用于包含粉丝信息的网页跳转。
				List<Article> artList=wechatService.queryReplyMaterialArticel(reply);
				
				if(null!=artList&&artList.size()>0){ 
					for(Article art:artList){
						art.setUrl(art.getUrl()+"?openId="+sm.getFromUserName());
					}
					respXML=doArticleMsg(sm,artList);
				}
			}
		}
		return respXML;
	}
	/**
	 * 响应客户端：返回文本类型消息
	 * @param sm
	 * @return
	 */
	private String doTextMsg(SuperMessage sm) {
		String respXML="";
		TextMessageResp text=new TextMessageResp();
		text.setCreateTime(new Date().getTime());
		text.setToUserName(sm.getFromUserName());
		text.setFromUserName(sm.getToUserName());
		text.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
		text.setContent(sm.getContent());
		respXML=MessageUtil.messageToXml(text);
		//System.out.println("========="+respXML);
		return respXML;
	}
	
	private String doArticleMsg(SuperMessage sm,List<Article> artList){
		String respXML="";
		NewsMessageResp news=new NewsMessageResp();
		news.setCreateTime(new Date().getTime());
		news.setFromUserName(sm.getToUserName());
		news.setToUserName(sm.getFromUserName());
		news.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		news.setArticleCount(artList.size());
		news.setArticles(artList);
		respXML=MessageUtil.messageToXml(news);
		//System.out.println("========="+respXML);
		return respXML;
	}
	
	
	

}